package com.ruoyi.common.utils;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * key值转换
 */
public class KeyConverter {

    /**
     * 将JSON字符串的 所有key值转换为小写
     * @param jsonNode
     * @return
     */
    public static JsonNode convertKeysToLowercase(JsonNode jsonNode) {
        ObjectMapper objectMapper = new ObjectMapper();

        if (jsonNode.isObject()) {
            ObjectNode objectNode = objectMapper.createObjectNode();

            jsonNode.fields().forEachRemaining(field -> {
                String lowercaseKey = field.getKey().toLowerCase();
                JsonNode value = convertKeysToLowercase(field.getValue());
                objectNode.set(lowercaseKey, value);
            });

            return objectNode;
        } else if (jsonNode.isArray()) {
            jsonNode.elements().forEachRemaining(KeyConverter::convertKeysToLowercase);
            return objectMapper.createArrayNode().addAll((ArrayNode) jsonNode);
        } else {
            return jsonNode;
        }
    }
}
